<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.sql.SQLException"%>
<%@page import="QRCG.Util"%>
<%@page import="QRCG.PlayGameServe"%>
<%@page import="QRCG.DatabaseManager"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Play A Game</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#play_game_map_canvas {
	height: 200px;
	width: 200px;
}
</style>

<script type="text/javascript"
	src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBOaAh2Iu9iwLfxzy9Poj3DSoa6nC4dK3I&sensor=false&region=TR"></script>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
  // A constant that points to a center of Istanbul.
  var ISTANBUL_LATLNG = new google.maps.LatLng(41.01721057822843,
      28.9764404296875);
  // HintID:Marker map.
  var markerMap = {};
  // HintID:Address
  var addressMap = {};
  var map; // The map object.

  // Classes & IDs of some HTML elements.
  var MAP_CANVAS_ID = 'play-game-map-canvas';

  function initialize() {
	  // Show/initialize map only if there will be some markers on it.
	  if (!jQuery.isEmptyObject(addressMap)) {
	    var myOptions = {
	      zoom : 8, // Zoom level. Greater number means closer.
	      center : ISTANBUL_LATLNG, // Initial central position of the map.
	      mapTypeId : google.maps.MapTypeId.ROADMAP
	    // Type of the map.
	    };
	    map = new google.maps.Map(document.getElementById(MAP_CANVAS_ID), myOptions);
	    for (point in addressMap) {
	    	addMarker(point, addressMap[point]);
	    }
	    delete addressMap;
	  }
  }

  /**
   * Adds a marker at a given location for the current selected hint.
   */
  function addMarker(hintId, coordinates) {
	   var nums = coordinates.substr(1, coordinates.length - 2).split(', ');
	   var location = new google.maps.LatLng(nums[0], nums[1]);
      // Create the new marker.
      var marker = new google.maps.Marker({
        position : location,
        map : map,
        title : 'Hint ' + hintId,
      });
      // Assign the new marker.
      markerMap[hintId] = marker;
  }
  
  /**
   * Adds a coordinate string to addressMap. This map will later bu used to create the map and
   * put markers on it. Any time it's called, addPoint is called before the loading is complete, hence
   * before initialize().
   */
  function addPoint(hintId, coordinates) {
	  addressMap[hintId] = coordinates;
  }
</script>
</head>

<%@ include file="header.jsp"%>

<body onload="initialize()">

	<%
		String keyword = request.getParameter("keyword");
		String sessionNickname = (String) session.getAttribute("nickname");

		String gameId = request.getParameter("game_id");
		if (!Util.hasTextContent(gameId)) {
			gameId = (String) request.getAttribute("game_id");
		}

		if (Util.hasTextContent(sessionNickname)) {

			session.setAttribute("keyword", "");
			session.setAttribute("game_id", gameId);

			// session.setAttribute("game_id", "");

		} else {
			if (Util.hasTextContent(keyword)) {
				session.setAttribute("keyword", keyword);
				session.setAttribute("game_id", gameId);
			} else {
				session.setAttribute("keyword", "");
				session.setAttribute("game_id", "");
			}
			request.setAttribute("message", "Please sign in first.");
		}

		DatabaseManager dbManager = new DatabaseManager();
		try {
			dbManager.connect();
		} catch (SQLException e) {
			request.setAttribute("levelMessage",
					"Something went wrong, please try reloading the page.");
		}

		String gameType = dbManager.getGameInformation(
				DatabaseManager.GameInformation.GAME_TYPE, gameId);
		boolean allAtOnce = false;
		if (Util.hasTextContent(gameType)) {
			allAtOnce = gameType.equalsIgnoreCase("0") ? false : true;
		}
	%>

	<%
		ArrayList<HashMap<String, Object>> userCompletedLevels = dbManager.getUserLevelHistory(
				gameId, sessionNickname);

		List<Object> completedLevelIdList = new ArrayList<Object>();
		for (HashMap<String, Object> row : userCompletedLevels) {
			completedLevelIdList.add(row.get("level_id"));
		}

		boolean inputEnabled = PlayGameServe.isInputEnabled(request, dbManager,
				sessionNickname, gameId);
	%>
<div class="information-text">
	<table align="center">
		<tr>
			<td>Please enter keyword of the QR code that you have scanned in the text area and submit.</td>
		</tr>
		<tr class="error-msg">
			<td>${message} ${level_message}</td>
		</tr>
	</table>
</div>

<div id="page">
<div id="page-bgtop">
	<div id="play-page">
		<div id="play-description">
			<div id="play-description-label">
				<div id="play-description-text">Game Information</div>
			</div>
			
			<table id="play-description-table" align="left">
					<%
						for (HashMap<String, Object> row : dbManager.getAllInformationOfGame(gameId)) {
					%>
					<tr>
						<td class="play-description-table-left">Game:</td>
						<td><%=(String) row.get("name")%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game Type:</td>
						<td><%=row.get("game_type").equals(0) ? "Step by step" : "All hints at once"%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game Creator:</td>
						<td><%=(String) row.get("nickname")%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game Description:</td>
						<td><%=(String) row.get("description")%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game begins:</td>
						<td><%=row.get("begin_date").toString()%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game ends:</td>
						<td><%=row.get("end_date").toString()%></td>
					</tr>
					<tr>
						<td class="play-description-table-left">Game takes place in:</td>
						<td><%=(String) row.get("location_name")%></td>
					</tr>
					<%
						}
					%>

			</table>
		</div>
		
		<div id="play-hint">
			<form action="PlayGameServe" method="post">
				<div>
					<table id="play-hint-table">
						<%
							if (allAtOnce) {
								for (HashMap<String, Object> row : dbManager.getAllLevelsOfGame(gameId)) {
						%>
						<tr>
							<td><input type="checkbox" name="vehicle" disabled
								<%=completedLevelIdList.contains(row.get("level_id")) ? "checked" : ""%> />
								<label class="play-hint-label">Hint #<%=row.get("level_id")%>
									: <%=row.get("hint")%></label></td>
						</tr>
						<%
							}
							} else {
						%>
						<tr>
							<td class="play-hint-label">Hint for Level #${current_level_id}:</td>
							<td>${current_level_hint}</td>
						</tr>
						<%
							}
							if (inputEnabled) {
								inputEnabled = dbManager.isUserRegisteredToGame(sessionNickname, gameId);
							}
						%>
						<tr>
							<td class="play-hint-label">Keyword:</td>
							<td><input class="play-hint-textbox"
								name=<%=allAtOnce ? "'keyword_all_at_once'" : "'keyword_step_by_step'"%>
								value="<%=keyword != null ? keyword : ""%>"
								<%=inputEnabled ? " " : "disabled"%>></td>
						</tr>
						<tr>
							<td><input type="hidden"
								value=${current_level_id
								} name="current_level_id" />
								<input type="hidden" value=${current_level_hint
								}
								name="current_level_hint" /></td>
							<td><input id="play-hint-button" type="submit"
								value="submit" <%=inputEnabled ? "" : "disabled"%>></td>
						</tr>
					</table>
					<div id="play-game-map-canvas"></div>
				</div>
			</form>
		</div>
		
		<div id="play-history">
			<div id="play-history-label">
				<div id="play-history-text">Level History</div>
			</div>
			<table id="play-history-table">
				<%
					for (HashMap<String, Object> row : userCompletedLevels) {
				%>
				<tr>
					<td class="play-history-table-left">Level <%=row.get("level_id")%> Hint:</td>
					<td><%=row.get("hint")%></td>
				</tr>
				<tr>
					<td class="play-history-table-left">Level <%=row.get("level_id")%> Keyword:</td>
					<td><%=row.get("level_code")%></td>
				</tr>
				<tr>
					<td align=center>*</td>
					<td align=center>*</td>
				</tr>
				<script type="text/javascript">addPoint('<%=row.get("level_id")%>', '<%=row.get("qr_address")%>')</script>
				<%
					}
				%>

				<%-- <%=PlayGameServe.getLevelHistory(request, dbManager)%> --%>

			</table>
		</div>
		
	</div>
</div>
</div>


<div style="clear: both;">&nbsp;</div>

</body>

<%@ include file="footer.jsp"%>
</html>